import pandas as pd
import sys
import os

def process_excel_file(file_path):
    """
    处理Excel文件，统计各个模块的测试结果
    """
    try:
        # 读取Excel文件的三个sheet
        must_pass_df = pd.read_excel(file_path, sheet_name='mustPass')
        possible_failed_df = pd.read_excel(file_path, sheet_name='possibleFailed')
        must_failed_df = pd.read_excel(file_path, sheet_name='mustFailed')
        
        print("成功读取Excel文件，开始处理数据...")
        
    except Exception as e:
        print(f"读取Excel文件失败: {e}")
        print("请确保文件存在且包含名为'mustPass', 'possibleFailed'和'mustFailed'的三个sheet")
        return None
    
    # 创建一个字典来存储统计结果
    module_stats = {}
    
    # 处理mustPass sheet
    print("处理mustPass sheet...")
    skipped_cases_mustPass = 0
    for index, row in must_pass_df.iterrows():
        module = str(row.iloc[0])  # 第一列：模块信息
        test_case = str(row.iloc[1])  # 第二列：用例名字
        
        # 检查是否有"未执行"的结果
        has_not_executed = False
        for col in range(2, len(row)):
            result = str(row.iloc[col]).strip() if pd.notna(row.iloc[col]) else ""
            if "未执行" in result:
                has_not_executed = True
                break
        
        # 只要有一次结果是"未执行"，就跳过该用例
        if has_not_executed:
            skipped_cases_mustPass += 1
            continue
        
        if module not in module_stats:
            module_stats[module] = {
                'pass_cases': set(),  # 使用集合存储用例，避免重复
                'assumption_failure_cases': set(),
                'ignore_cases': set(),
                'possible_fail_cases': set(),
                'must_fail_cases': set()
            }
        
        # 检查运行结果列（从第三列开始）
        has_pass = False
        has_assumption_failure = False
        has_ignore = False
        
        for col in range(2, len(row)):
            result = str(row.iloc[col]).strip() if pd.notna(row.iloc[col]) else ""
            
            if 'PASS' in result.upper():
                has_pass = True
            if 'ASSUMPTION_FAILURE' in result.upper():
                has_assumption_failure = True
            if 'IGNORE' in result.upper():
                has_ignore = True
        
        # 根据优先级分配用例：PASS > ASSUMPTION_FAILURE > IGNORE
        if has_pass:
            module_stats[module]['pass_cases'].add(test_case)
        elif has_assumption_failure:
            module_stats[module]['assumption_failure_cases'].add(test_case)
        elif has_ignore:
            module_stats[module]['ignore_cases'].add(test_case)
    
    print(f"  在mustPass sheet中跳过了 {skipped_cases_mustPass} 个包含'未执行'结果的用例")
    
    # 处理possibleFailed sheet
    print("处理possibleFailed sheet...")
    skipped_cases_possibleFailed = 0
    for index, row in possible_failed_df.iterrows():
        module = str(row.iloc[0])  # 第一列：模块信息
        test_case = str(row.iloc[1])  # 第二列：用例名字
        
        # 检查是否有"未执行"的结果
        has_not_executed = False
        for col in range(2, len(row)):
            result = str(row.iloc[col]).strip() if pd.notna(row.iloc[col]) else ""
            if "未执行" in result:
                has_not_executed = True
                break
        
        # 只要有一次结果是"未执行"，就跳过该用例
        if has_not_executed:
            skipped_cases_possibleFailed += 1
            continue
        
        if module not in module_stats:
            module_stats[module] = {
                'pass_cases': set(),
                'assumption_failure_cases': set(),
                'ignore_cases': set(),
                'possible_fail_cases': set(),
                'must_fail_cases': set()
            }
        
        # possibleFailed sheet中的用例直接归为possible_fail
        module_stats[module]['possible_fail_cases'].add(test_case)
    
    print(f"  在possibleFailed sheet中跳过了 {skipped_cases_possibleFailed} 个包含'未执行'结果的用例")
    
    # 处理mustFailed sheet
    print("处理mustFailed sheet...")
    skipped_cases_mustFailed = 0
    for index, row in must_failed_df.iterrows():
        module = str(row.iloc[0])  # 第一列：模块信息
        test_case = str(row.iloc[1])  # 第二列：用例名字
        
        # 检查是否有"未执行"的结果
        has_not_executed = False
        for col in range(2, len(row)):
            result = str(row.iloc[col]).strip() if pd.notna(row.iloc[col]) else ""
            if "未执行" in result:
                has_not_executed = True
                break
        
        # 只要有一次结果是"未执行"，就跳过该用例
        if has_not_executed:
            skipped_cases_mustFailed += 1
            continue
        
        if module not in module_stats:
            module_stats[module] = {
                'pass_cases': set(),
                'assumption_failure_cases': set(),
                'ignore_cases': set(),
                'possible_fail_cases': set(),
                'must_fail_cases': set()
            }
        
        # mustFailed sheet中的用例直接归为must_fail
        module_stats[module]['must_fail_cases'].add(test_case)
    
    print(f"  在mustFailed sheet中跳过了 {skipped_cases_mustFailed} 个包含'未执行'结果的用例")
    
    # 创建结果DataFrame
    result_data = []
    for module, stats in module_stats.items():
        result_data.append([
            module,
            len(stats['pass_cases']),
            len(stats['assumption_failure_cases']),
            len(stats['ignore_cases']),
            len(stats['possible_fail_cases']),
            len(stats['must_fail_cases'])
        ])
    
    result_df = pd.DataFrame(
        result_data,
        columns=['模块', 'PASS用例数', 'ASSUMPTION_FAILURE用例数', 'IGNORE用例数', 'possible_fail用例数', 'must_fail用例数']
    )
    
    # 按模块名排序
    result_df = result_df.sort_values('模块')
    
    # 添加总计行
    total_row = pd.DataFrame([['总计', 
                              result_df['PASS用例数'].sum(),
                              result_df['ASSUMPTION_FAILURE用例数'].sum(),
                              result_df['IGNORE用例数'].sum(),
                              result_df['possible_fail用例数'].sum(),
                              result_df['must_fail用例数'].sum()]],
                            columns=result_df.columns)
    result_df = pd.concat([result_df, total_row], ignore_index=True)
    
    # 保存结果到新的Excel文件
    output_file = file_path.replace('.xlsx', '_统计结果.xlsx')
    
    # 使用ExcelWriter创建包含多个sheet的Excel文件
    with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
        # 写入统计结果
        result_df.to_excel(writer, sheet_name='统计结果', index=False)
        
        # 写入原始数据用于参考
        must_pass_df.to_excel(writer, sheet_name='mustPass原始数据', index=False)
        possible_failed_df.to_excel(writer, sheet_name='possibleFailed原始数据', index=False)
        must_failed_df.to_excel(writer, sheet_name='mustFailed原始数据', index=False)
    
    print(f"\n处理完成！")
    print(f"共处理了 {len(module_stats)} 个模块")
    print(f"结果已保存到: {output_file}")
    
    # 显示汇总信息
    total_skipped = skipped_cases_mustPass + skipped_cases_possibleFailed + skipped_cases_mustFailed
    print(f"\n跳过的用例统计:")
    print(f"  mustPass sheet: {skipped_cases_mustPass} 个用例")
    print(f"  possibleFailed sheet: {skipped_cases_possibleFailed} 个用例")
    print(f"  mustFailed sheet: {skipped_cases_mustFailed} 个用例")
    print(f"  总计跳过: {total_skipped} 个包含'未执行'结果的用例")
    
    print("\n汇总统计:")
    print(f"总PASS用例数: {result_df.iloc[-1, 1]}")
    print(f"总ASSUMPTION_FAILURE用例数: {result_df.iloc[-1, 2]}")
    print(f"总IGNORE用例数: {result_df.iloc[-1, 3]}")
    print(f"总possible_fail用例数: {result_df.iloc[-1, 4]}")
    print(f"总must_fail用例数: {result_df.iloc[-1, 5]}")
    
    return result_df

def main():
    # 检查命令行参数
    if len(sys.argv) != 2:
        print("使用方法: python calculate_total.py <Excel文件路径>")
        print("例如: python calculate_total.py a.xlsx")
        sys.exit(1)
    
    file_path = sys.argv[1]
    
    # 检查文件是否存在
    if not os.path.exists(file_path):
        print(f"错误: 文件 '{file_path}' 不存在!")
        sys.exit(1)
    
    # 处理Excel文件
    process_excel_file(file_path)

if __name__ == "__main__":
    main()